/**
 * Created by yanlin on 2017/10/24.
 */

var role = $("input[name='role']").val();

var stnm_message = new Ext.data.JsonStore({
    url: '/qtIndex/stationIdAndNm/combo.action',
    fields: ['value', 'text']
});
stnm_message.load();
var stnm_message_combo_add = new Ext.form.ComboBox({
    name: 'stnm',
    fieldLabel: '测站名称',
    emptyText: '请选择',
    mode: 'local',
    editable: true,
    triggerAction: 'all',
    store: stnm_message,
    width: 150,
    valueField: 'value', // 值
    displayField: 'text',
    hiddenName: 'stcd',
    allowBlank: false,
    msgTarget: "side",
    selectOnFocus: true,
    queryParam: 'userinput',
    forceSelection: true,
    listeners: {
        beforequery: function (qe) {
            var para = qe.query;
        }
    }
});
var stnm_message_combo_upd = new Ext.form.ComboBox({
    name: 'stnm',
    fieldLabel: '测站名称',
    emptyText: '请选择',
    mode: 'local',
    editable: true,
    triggerAction: 'all',
    store: stnm_message,
    width: 150,
    valueField: 'value', // 值
    displayField: 'text',
    hiddenName: 'stcd',
    allowBlank: false,
    msgTarget: "side",
    queryParam: 'userinput',
    forceSelection: true,
    listeners: {
        beforequery: function (qe) {
            var para = qe.query;
        }
    }
});

var lskzm_reader = new Ext.data.JsonReader({
    totalProperty: 'totalProperty',
    root: 'root'
}, [
    {
        name: 'stcd'
    }, {
        name: 'swswcd'
    }, {
        name: 'ylcd'
    }, {
        name: 'szcd'
    }, {
        name: 'nt'
    }
]);

var lskzm_addform = new Ext.form.FormPanel({
    labelAlign: 'right',
    frame: true,
    labelWidth: 150,
    url: '/qtIndex/lskzmdygx/add.action',
    bodyStyle: 'padding:30px',
    reader: lskzm_reader,
    items: [
        stnm_message_combo_add,
        {
            xtype: 'textfield',
            fieldLabel: '水文水位站码',
            width: 150,
            name: 'swswcd'
        },
        {
            xtype: 'textfield',
            fieldLabel: '雨量站码',
            width: 150,
            name: 'ylcd'
        },
        {
            xtype: 'textfield',
            fieldLabel: '水质站码',
            width: 150,
            name: 'szcd'
        },
        {
            xtype: 'textarea',
            fieldLabel: '备注',
            width: 150,
            name: 'nt'
        }
    ]
});
var lskzm_updform = new Ext.form.FormPanel({
    labelAlign: 'right',
    frame: true,
    labelWidth: 150,
    url: '/qtIndex/lskzmdygx/update.action',
    bodyStyle: 'padding:30px',
    reader: lskzm_reader,
    items: [
        //stnm_message_combo_upd,
        {
            xtype: 'textfield',
            fieldLabel: '测站编码',
            readOnly: true,
//                disabled :true,
            width: 150,
            name: 'stcd',
            allowBlank: false,
            msgTarget: "side"
        },
        {
            xtype: 'textfield',
            fieldLabel: '测站名称',
            readOnly: true,
            width: 150,
            name: 'stnm'
        },
        {
            xtype: 'textfield',
            fieldLabel: '水文水位站码',
            width: 150,
            name: 'swswcd'
        },
        {
            xtype: 'textfield',
            fieldLabel: '雨量站码',
            width: 150,
            name: 'ylcd'
        },
        {
            xtype: 'textfield',
            fieldLabel: '水质站码',
            width: 150,
            name: 'szcd'
        },
        {
            xtype: 'textarea',
            fieldLabel: '备注',
            width: 150,
            name: 'nt'
        }
    ]
});


$(document).ready(function () {

    if (role != 0 && role!= 1) {
        $("#add_button").attr('style', "display:none");
    }

    $.post("/qtIndex/xzqhName.action", function (data) {
        //console.log(data);
        $("#header").text(data + "历史库站码对应关系对照表");
        // if (data == "宁波市") {
        //     $("#add_button").attr('style', "display:none");
        // }

    });
    var t = $('#lskzm').DataTable({
        serverSide: true,
        ajax: {
            url: '/qtIndex/lskzmdygx/all.action',
            type: 'POST'
        },
        "scrollY": 500,
        "scrollX": true,
        "ordering": false,
        "columnDefs": [{
            "searchable": false,
            "orderable": false,
            "targets": 0
        },
        //     {
        //     'targets': 1,
        //     // 'checkboxes': {
        //     //     'selectRow': true
        //     // }
        //     'searchable': false,
        //     'orderable': false,
        //     'className': 'dt-body-center'
        // },
        {
            'targets': 7
        }
        ],
        "order": [[1, 'asc']],
        "columns": [
            {"defaultContent": ""},//第0列
            //第1列
            // {
            //     render: function (data, type, full, meta) {
            //         return '<input type="checkbox" name="id[]" value="' + full.stcd + '">';
            //     }
            // },
            //第2列
            {"data": "stnm", "defaultContent": ""},
            {
                "data": "stcd", "defaultContent": ""
            },
            {"data": "swswcd", "defaultContent": ""},
            {"data": "ylcd", "defaultContent": ""},
            {"data": "szcd", "defaultContent": ""},
            {"data": "nt", "defaultContent": ""},
            {
                render: function (a, b, c, d) {
                    //c为当前行的对象
                    // console.log(c);
                    if(role == 0 || role == 1){
                        return "<a onclick= edit('" + c.stcd + "')><img src='/jsps/qt/images/caozuo.png' title='修改'></a>";
                    }else{
                        $("#action").css("display","none");
                        $("#header").attr('style','margin-bottom: 25px');
                        return "";
                    }
                }
            }
        ],
        "pagingType": "full_numbers",
        "pageLength": 30,
        "dom": '<"toolbar">rtip',
        "language": {
            "lengthMenu": "每页 _MENU_ 条记录",
            "zeroRecords": "没有找到记录",
            "info": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
            "infoEmpty": "无记录",
            "infoFiltered": "(从 _MAX_ 条记录过滤)",
            "sSearch": "查询:",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": " 上一页 ",
                "sNext": " 下一页 ",
                "sLast": " 尾页"
            }
        }
    });

    t.on('draw.dt', function () {
        // $('#lskzm-select-all').attr("checked", false);
        t.column(2).visible(false);
        t.column(0, {
            search: 'applied',
            order: 'applied'
        }).nodes().each(function (cell, i) {
            //i 从0开始，所以这里先加1
            i = i + 1;
            //服务器模式下获取分页信息，使用 DT 提供的 API 直接获取分页信息
            var page = t.page.info();
            //当前第几页，从0开始
            var pageno = page.page;
            //每页数据
            var length = page.length;
            //行号等于 页数*每页数据长度+行号
            var columnIndex = (i + pageno * length);
            cell.innerHTML = columnIndex;
        });
    });

    t.on('search.dt', function () {
        // $.get("/qtIndex/station/getByNmOrId.action?&srh="+encodeURI(encodeURI(t.search())), function (data, status) {
        //     // var json = jQuery.parseJSON(data);
        //     // // $("div.toolbar").html('<b id="count" style="color:#009fff;position:absolute;padding:0px;display: block">水文水位站 ' + json[0] + ' 处,降水蒸发站' + json[1] + '处,实时雨水情' + json[2] + '处,水质站' + json[3] + '处</b>');
        //     // $("div.toolbar").html('<b id="count" style="color:#009fff;position:absolute;padding:0px;display: block">水文水位站 <a onclick="showH()" style="cursor: hand">' + json[0] + '</a> 处,降水蒸发站 <a onclick="showP()" style="cursor: hand">' + json[1] + ' </a>处,实时雨水情 <a onclick="showS()" style="cursor: hand">' + json[2] + ' </a>处,水质站 <a onclick="showW()" style="cursor: hand">' + json[3] + '</a> 处</b>');
        // });
    });

    $('#search_button').on('click',function () {
        var srh = $("input[name='search_text']").val();
        t.search(srh).draw();
    });
    $("#search_input").bind('keyup',function (e) {
        if(e.keyCode == 13){//回车事件
            var srh = $("input[name='search_text']").val();
            t.search(srh).draw();
        }
    });

    // $('#lskzm-select-all').on('click', function () {
    //     // Get all rows with search applied
    //     var rows = t.rows({'search': 'applied'}).nodes();
    //     // Check/uncheck checkboxes for all rows in the table
    //     $('input[type="checkbox"]', rows).prop('checked', this.checked);
    // });

    $('#add_button').on('click', function (e) {
        Ext.onReady(function () {
            var add_form = lskzm_addform;
            var add_win = new Ext.Window({
                layout: 'fit',
                title: '历史库站码对应关系添加',
                width: '500',
                height: '400',
                closeAction: 'hide',
                constrain: true,
                buttonAlign: 'center',
                resizable: false,
                modal: true,
                plain: true,
                items: [add_form],
                buttons: [
                    {
                        text: '增加',
                        handler: function () {
                            add_form.getForm().submit({
                                success: function (form, action) {
                                    Ext.Msg.alert('提示',
                                        '提交成功！');
                                    add_form.getForm().reset();
                                    add_win.hide();
                                    t.ajax.reload();
                                },
                                failure: function () {
                                    Ext.Msg.alert('提示',
                                        '提交失败,记录已存在！');
                                }
                            });
                        }
                    },
                    {
                        text: '取消',
                        handler: function () {
                            add_win.hide();
                        }
                    }
                ]
            });
            add_win.on('show', function () {
            });
            add_win.show();
        });
    });
});

function edit(stcd) {
    Ext.onReady(function () {
        var upp_form = lskzm_updform;
        var upp_win = new Ext.Window({
            layout: 'fit',
            title: '历史库站码对应关系修改',
            width: '500',
            height: '400',
            closeAction: 'hide',
            constrain: true,
            buttonAlign: 'center',
            resizable: false,
            modal: true,
            plain: true,
            items: [upp_form],
            buttons: [
                {
                    text: '修改',
                    handler: function () {
                        upp_form.getForm().submit({
                            success: function (form, action) {
                                Ext.Msg.alert('提示',
                                    '提交成功！', function () {
                                        history.go();
                                    });
                                upp_form.getForm().reset();
                                upp_win.hide();
                            },
                            failure: function () {
                                Ext.Msg.alert('提示',
                                    '提交失败，请检查输入数据项！');
                            }

                        });
                    }
                },
                {
                    text: '取消',
                    handler: function () {
                        upp_win.hide();
                    }
                }
            ]
        });

        upp_win.on('show', function () {
            Ext.Ajax.request({
                url: '/qtIndex/lskzmdygx/getById.action?id=' + stcd,
                success: function (resp, opts) {
                    //console.log("response:"+resp);
                    var respText = Ext.util.JSON.decode(resp.responseText);
                    upp_form.getForm().findField('stcd').setValue(respText.stcd);
                    upp_form.getForm().findField('stnm').setValue(respText.stnm);
                    upp_form.getForm().findField('swswcd').setValue(respText.swswcd);
                    upp_form.getForm().findField('ylcd').setValue(respText.ylcd);
                    upp_form.getForm().findField('szcd').setValue(respText.szcd);
                    upp_form.getForm().findField('nt').setValue(respText.nt);
                }

            });
        });
        upp_win.show();

    });
}